package opn.srn.plugin;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Properties;

public class PluginManager {
	List<IPlugin> plugins = new ArrayList<IPlugin>();

	public void startPlugins(Collection<File> files) throws Exception {
		for (File file : files) {
			Properties prop = new Properties();
			prop.load(new FileInputStream(file));
			String pluginClassNamesList = prop.getProperty("plugins");
			if (pluginClassNamesList == null || pluginClassNamesList.isEmpty()) {
				continue;
			}

			String[] pluginClassNames = pluginClassNamesList.split(",");
			if (pluginClassNames == null || pluginClassNames.length == 0) {
				continue;
			}

			String pluginFolder = file.getParent();
			startPlugins(Arrays.asList(pluginClassNames), new PluginContext(pluginFolder));
		}
	}

	public void startPlugins(Collection<String> clazzNames, PluginContext context) throws Exception {
		for (String pluginClassNames : clazzNames) {
			Class<?> pluginClass = Class.forName(pluginClassNames);
			IPlugin plugin = (IPlugin) pluginClass.newInstance();
			plugin.start(context);
			plugins.add(plugin);
		}
	}

	public void stopPlugins() throws Exception {
		for (IPlugin plugin : plugins) {
			plugin.stop(null);
		}
		plugins.clear();
	}

}
